package com.education.common;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @author 余一
 * @date 2021/9/14  9:47
 */
@Component
//实现Spring Bean生命周期接口ApplicationContextAware
public class SpringBeanManager implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    @Override
    public void destroy() throws Exception {
        if (applicationContext != null) {
            applicationContext = null;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringBeanManager.applicationContext == null) {
            SpringBeanManager.applicationContext = applicationContext;
        }
        System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringBeanManager.applicationContext+"========");
    }

    public static <T> T getBean(String name) {
        return (T) SpringBeanManager.applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return (T) SpringBeanManager.applicationContext.getBean(clazz);
    }
}
